import time
import requests
import json
import os
import subprocess

# 条件导入GPIO库，如果在非树莓派环境下运行则使用模拟库
try:
    import RPi.GPIO as GPIO
    ON_RASPBERRY_PI = True
except ImportError:
    class GPIOSimulator:
        BCM = 1
        OUT = 1
        HIGH = 1
        LOW = 0
        @staticmethod
        def setmode(mode):
            pass
        @staticmethod
        def setup(pin, mode):
            pass
        @staticmethod
        def output(pin, value):
            pass
        @staticmethod
        def cleanup():
            pass
    GPIO = GPIOSimulator()
    ON_RASPBERRY_PI = False


def alarm_on():
    PIN_ID=23
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(PIN_ID, GPIO.OUT)
    GPIO.output(PIN_ID, GPIO.LOW)
    
    GPIO.output(PIN_ID, GPIO.HIGH)
    time.sleep(2.0)
    GPIO.output(PIN_ID, GPIO.LOW)

    GPIO.cleanup()

def alarm():
    alarm_on()


def get_image():
    # 先尝试一次采集，若失败或生成文件为空，再重试一次
    def attempt_capture():
        try:
            if os.path.exists("image.jpg"):
                os.remove("image.jpg")
        except Exception:
            # 删除失败不影响后续采集
            pass
        return subprocess.run(
            "fswebcam --no-banner -r 640x480 image.jpg",
            shell=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        ).returncode

    rc = attempt_capture()
    # 若返回码非0，或文件不存在/空文件，则等待片刻并重试一次
    if (not os.path.isfile("image.jpg")) or os.path.getsize("image.jpg") == 0:
        time.sleep(0.5)
        attempt_capture()


def detect():
    url = "http://192.168.1.253:8800/api/v1/recognition/recognize?limit=1"
    url = "https://101.70.156.105:53992/api/v1/recognition/recognize?limit=1"
    # params = {"face_plugins": "landmarks, gender, age, pose"}
    params = {}
    headers = {
        "x-api-key": "71f17ddc-bcc3-47f8-8e7c-b10911a29802"
    }
    
    with open("image.jpg", "rb") as f:
        files = {"file": f}
        response = requests.post(url, params=params, headers=headers, files=files, verify=False)
    
    label = ''
    data = json.loads(response.text)
    print(response.text)
    if 'message' in data and data['message'] == 'No face is found in the given image':
        print('没有检测到人脸')
        label = '没有人'
    elif 'result' in data and len(data["result"]) > 0:
        item = data["result"][0]
        subj = item["subjects"][0]
        print("subject:", subj["subject"])
        print("similarity:", subj["similarity"])
        if float(subj["similarity"]) <=0.99:
            print("这是陌生人")
            label = '陌生人'
        else:
            print("这是家人")
            label = '熟人'
        
    return label